#!/bin/sh

## hyphop ##

#DIR=`dirname $0`
#NAME=`basename $0`

NAME=${0/*\/}

DIR=${0%/$NAME}

WPA_CONF=/etc/wifi.net.conf
CONF=$WPA_CONF

about(){ echo "\
$NAME - config wifi net

USAGE

    $NAME net [ password ] [ prio ] [ disabled ] [new] - add net

    $NAME		- show current config
    $NAME -reset	- reset (clear) config

    new=1 $NAME NET_NAME PASSWORD  - rewrite config file & add net 

MULTILINE CONFIG USAGE

    $NAME - < CONFIG_FILE

CONFIG_FILE FORMAT

its simple line by line config 

    net [ password ] [ prio ] [ disabled ]
    ...

NOTE 

    strings with spaces must quoted as \"my cool network name\"

CONFIG

    $CONF, /etc/wifi.conf

SEE ALSO

    help wifi,  wifi.*

";
}

for i in "$@"; do 
case $i in

	-h|--help)
	    about
	    exit 0
	;;
	-reset|-new|-clear)
	    new=1
	;;
	
esac done

[ "$new" ] || new="$5"

[ -f $CONF ] || new=1
[ -s $CONF ] || new=1

grep -q ctrl_interface $CONF || new=1

[ "$new" ] && {
echo "[i] reset config"
echo "# generated by $(basename $0)
ctrl_interface=/var/run/wpa_supplicant
update_config=1
ap_scan=1
" > $CONF

}

[ -f $CONF ] || {
    echo "[w] net config not found at $CONF" >&2
    echo "[i] run wifi.config SSID PASSWORD [ PRIO ]" >&2
    exit 1
}

addline() { 

net="$1"
password="$2"
prio="$3"
[ "$prio" = "" ] && prio=10
disabled="$4"


[ "$disabled" = "" ] && disabled=0

[ "$password" = "" ] && {
LINE="
network={
        ssid=\"$net\"
#       psk=\"\"
#       key_mgmt=WPA-PSK
        priority=$prio
        disabled=$disabled
}
"

}

[ "$password" = "" ] || {
LINE="
network={
        ssid=\"$net\"
        psk=\"$password\"
        key_mgmt=WPA-PSK
        priority=$prio
        disabled=$disabled
}
"
}


echo "[i] $NAME ADD net: \"$net\", password: \"$password\", prio: $prio, disabled: $disabled >> $CONF"

[ "$verbose" ] && echo "[BEGIN]
$LINE
[END]
"

grep -q "ssid=\"$net\"" $CONF  && {
    echo "[i] $NAME config: $CONF have net: \"$net\" already! plz change config by handzzz ;)"
    exit 1
}

echo "$LINE" >> $CONF

}


[ "$1" = "-" ] && {
    echo "[i] $NAME read by line">&2
    while read l ; do
	echo "$l"
	eval addline $l
    done
    exit 0
}

[ "$1" ] || {
    echo "[i] $NAME display $CONF">&2
    cat $CONF
    exit 1
}


addline "$@" 

